import 'dart:math' as math;
import 'package:intl/intl.dart';
import 'package:flutter/foundation.dart';
import '../models/period_model.dart';
import 'package:moonmate/services/shared_preferences_service.dart';
import 'database_helper.dart';

// 临时预测数据类，用于getTodayPrediction返回
class TodayPrediction {
  final String status;
  final String advice;
  final bool isPeriod;
  final bool isOvulation;
  final dynamic cycleInfo; // 用于兼容现有代码
  final String discharge;
  final List<String> symptoms;
  
  TodayPrediction({
    required this.status,
    required this.advice,
    required this.isPeriod,
    required this.isOvulation,
    this.cycleInfo,
    this.discharge = '正常',
    this.symptoms = const [],
  });
}

class PeriodService {
  final SharedPreferencesService _prefsService;
  final DatabaseHelper _databaseHelper = DatabaseHelper.instance;
  final DateFormat _dateFormat = DateFormat('yyyy-MM-dd');

  PeriodService() : _prefsService = SharedPreferencesService() {
    _prefsService.initialize();
  }

  // 记录经期
  Future<bool> recordPeriod(Period period) async {
    try {
      final periodMap = {
        'id': period.id ?? DateTime.now().millisecondsSinceEpoch.toString(),
        'start_date': _dateFormat.format(period.startDate),
        'end_date': _dateFormat.format(period.endDate),
        'flow': period.flowIntensity,
        'note': period.note,
        'user_id': period.userId,
      };
      return await _prefsService.addObjectToList(SharedPreferencesService.keyPeriods, periodMap);
    } catch (e) {
      debugPrint('记录经期失败: $e');
      return false;
    }
  }

  // 获取用户所有经期记录（返回原始数据格式）
  Future<List<Map<String, dynamic>>> getUserPeriods(int userId) async {
    try {
      final allPeriods = _prefsService.getObjectList(SharedPreferencesService.keyPeriods);
      return allPeriods
          .where((period) => period['user_id'] == userId)
          .toList()
          ..sort((a, b) => b['start_date'].compareTo(a['start_date']));
    } catch (e) {
      debugPrint('获取用户所有经期记录失败: $e');
      return [];
    }
  }

  // 获取用户所有经期记录（返回Period对象）
  Future<List<Period>> getUserPeriodsAsObjects(int userId) async {
    final maps = await getUserPeriods(userId);
    return List.generate(maps.length, (i) {
      return Period(
        id: maps[i][DatabaseHelper.columnPeriodId],
        startDate: DateTime.parse(maps[i][DatabaseHelper.columnPeriodStart]),
        endDate: DateTime.parse(maps[i][DatabaseHelper.columnPeriodEnd]),
        flowIntensity: maps[i][DatabaseHelper.columnPeriodFlow],
        note: maps[i][DatabaseHelper.columnPeriodNote],
        userId: maps[i][DatabaseHelper.columnPeriodUserId],
      );
    });
  }

  // 获取用户所有症状记录
  Future<List<Map<String, dynamic>>> getUserSymptoms(int userId) async {
    try {
      final allSymptoms = _prefsService.getObjectList(SharedPreferencesService.keySymptoms);
      return allSymptoms
          .toList()
          ..sort((a, b) => b['date'].compareTo(a['date']));
    } catch (e) {
      debugPrint('获取用户所有症状记录失败: $e');
      return [];
    }
  }

  // 记录症状
  Future<bool> recordSymptom(Symptom symptom) async {
    try {
      final symptomMap = {
        'id': symptom.id ?? DateTime.now().millisecondsSinceEpoch.toString(),
        'name': symptom.name,
        'severity': symptom.severity,
        'date': _dateFormat.format(symptom.date),
        'period_id': symptom.periodId,
      };
      return await _prefsService.addObjectToList(SharedPreferencesService.keySymptoms, symptomMap);
    } catch (e) {
      debugPrint('记录症状失败: $e');
      return false;
    }
  }

  // 获取特定日期范围的症状
  Future<List<Symptom>> getSymptomsByDateRange(DateTime startDate, DateTime endDate) async {
    final db = await _databaseHelper.database;
    final List<Map<String, dynamic>> maps = await db.query(
      DatabaseHelper.tableSymptom,
      where: '${DatabaseHelper.columnSymptomDate} >= ? AND ${DatabaseHelper.columnSymptomDate} <= ?',
      whereArgs: [_dateFormat.format(startDate), _dateFormat.format(endDate)],
    );

    return List.generate(maps.length, (i) {
      return Symptom(
        id: maps[i][DatabaseHelper.columnSymptomId],
        name: maps[i][DatabaseHelper.columnSymptomName],
        severity: maps[i][DatabaseHelper.columnSymptomSeverity],
        date: DateTime.parse(maps[i][DatabaseHelper.columnSymptomDate]),
        periodId: maps[i][DatabaseHelper.columnSymptomPeriodId],
      );
    });
  }

  // 预测下一次经期
  Future<List<PeriodPrediction>> predictNextPeriods(int userId, int count) async {
    // 获取用户的经期记录
    final periods = await getUserPeriodsAsObjects(userId);
    if (periods.isEmpty) {
      return [];
    }

    // 计算平均周期和经期长度
    final cycleData = calculateAverageCycleData(periods);
    final avgCycleLength = cycleData['avgCycleLength'];
    final avgPeriodLength = cycleData['avgPeriodLength'];

    // 获取最近一次经期
    final latestPeriod = periods.first;
    final predictions = <PeriodPrediction>[];

    // 生成预测
    for (int i = 1; i <= count; i++) {
      // 预测下次经期开始日期
      final predictedStartDate = latestPeriod.startDate.add(Duration(days: (avgCycleLength! * i).toInt()));
      // 预测下次经期结束日期
      final predictedEndDate = predictedStartDate.add(Duration(days: (avgPeriodLength! - 1).toInt()));
      
      // 计算预测准确率
      final accuracy = calculatePredictionAccuracy(periods.length).toDouble();
      
      predictions.add(PeriodPrediction(
        startDate: predictedStartDate,
        endDate: predictedEndDate,
        accuracy: accuracy,
        type: 'period',
      ));
    }

    return predictions;
  }

  // 预测排卵期
  Future<List<PeriodPrediction>> predictOvulationPeriod(int userId, int months) async {
    // 获取用户的经期记录
    final periods = await getUserPeriodsAsObjects(userId);
    if (periods.isEmpty) {
      return [];
    }

    // 计算平均周期长度
    final cycleData = calculateAverageCycleData(periods);
    final avgCycleLength = cycleData['avgCycleLength'];

    // 获取最近一次经期
    final latestPeriod = periods.first;
    final predictions = <PeriodPrediction>[];

    // 生成未来几个月的排卵期预测
    for (int i = 0; i < months; i++) {
      // 计算每个周期的排卵期（通常在下次月经前14天）
      final nextPeriodStart = latestPeriod.startDate.add(Duration(days: (avgCycleLength! * (i + 1)).toInt()));
      final ovulationDate = nextPeriodStart.subtract(Duration(days: 14));
      
      // 排卵期前后各一天也视为易孕期
      final fertileStart = ovulationDate.subtract(Duration(days: 1));
      final fertileEnd = ovulationDate.add(Duration(days: 1));
      
      // 计算预测准确率
      final accuracy = calculatePredictionAccuracy(periods.length).toDouble();
      
      predictions.add(PeriodPrediction(
        startDate: fertileStart,
        endDate: fertileEnd,
        accuracy: accuracy,
        type: 'ovulation',
      ));
    }

    return predictions;
  }

  // 预测安全期
  Future<List<PeriodPrediction>> predictSafePeriod(int userId, int months) async {
    final periods = await getUserPeriodsAsObjects(userId);
    
    if (periods.isEmpty) {
      return [];
    }

    // 计算平均周期数据
    final cycleData = calculateAverageCycleData(periods);
    final avgCycleLength = cycleData['avgCycleLength'];
    final avgPeriodLength = cycleData['avgPeriodLength'];

    // 获取最近一次经期
    final latestPeriod = periods.first;
    final predictions = <PeriodPrediction>[];

    // 为每个月生成安全期预测
    for (int i = 0; i < months; i++) {
      // 计算每个周期的开始和结束
      final cycleStart = latestPeriod.startDate.add(Duration(days: (avgCycleLength! * i).toInt()));
      final cycleEnd = cycleStart.add(Duration(days: (avgCycleLength - 1).toInt()));
      
      // 经期后安全期：经期结束到排卵期前
      final periodEnd = cycleStart.add(Duration(days: avgPeriodLength!));
      final ovulationStart = cycleEnd.subtract(Duration(days: 16)); // 排卵期前2天
      
      if (periodEnd.isBefore(ovulationStart)) {
        predictions.add(PeriodPrediction(
          startDate: periodEnd,
          endDate: ovulationStart.subtract(Duration(days: 1)),
          accuracy: calculatePredictionAccuracy(periods.length).toDouble(),
          type: 'safe',
        ));
      }
      
      // 排卵后安全期：排卵期后到下次经期开始
      final ovulationEnd = cycleEnd.subtract(Duration(days: 12)); // 排卵期后2天
      final nextPeriodStart = cycleEnd.add(Duration(days: 1));
      
      if (ovulationEnd.isBefore(nextPeriodStart)) {
        predictions.add(PeriodPrediction(
          startDate: ovulationEnd.add(Duration(days: 1)),
          endDate: nextPeriodStart.subtract(Duration(days: 1)),
          accuracy: calculatePredictionAccuracy(periods.length).toDouble(),
          type: 'safe',
        ));
      }
    }

    return predictions;
  }

  // 计算平均周期数据
  Map<String, int> calculateAverageCycleData(List<Period> periods) {
    if (periods.length < 2) {
      return { 'avgCycleLength': 28, 'avgPeriodLength': 5 };
    }

    int totalCycleLength = 0;
    int totalPeriodLength = 0;
    int count = math.min(periods.length - 1, 6); // 最多使用最近6个周期计算

    for (int i = 0; i < count; i++) {
      // 计算周期长度（两次月经开始之间的天数）
      final cycleLength = periods[i].startDate.difference(periods[i + 1].startDate).inDays.abs();
      totalCycleLength += cycleLength;
      
      // 计算经期长度
      final periodLength = periods[i].endDate.difference(periods[i].startDate).inDays + 1;
      totalPeriodLength += periodLength;
    }

    final avgCycleLength = (totalCycleLength / count).round();
    final avgPeriodLength = (totalPeriodLength / math.min(periods.length, 6)).round();

    // 添加一些合理性检查
    return {
      'avgCycleLength': avgCycleLength.clamp(21, 35),
      'avgPeriodLength': avgPeriodLength.clamp(3, 7),
    };
  }

  // 计算预测准确率
  double calculatePredictionAccuracy(int periodCount) {
    if (periodCount < 1) return 0.0;
    if (periodCount < 3) return 0.7;   // 1-2个周期，70%准确率
    if (periodCount < 6) return 0.85;  // 3-5个周期，85%准确率
    return 0.98;  // 6个以上周期，98%准确率
  }

  // 生成周期性健康报告
  Future<HealthReport> generateHealthReport(int userId, DateTime startDate, DateTime endDate) async {
    // 获取时间范围内的经期记录
    final db = await _databaseHelper.database;
    final List<Map<String, dynamic>> periodMaps = await db.query(
      DatabaseHelper.tablePeriod,
      where: '${DatabaseHelper.columnPeriodUserId} = ? AND ${DatabaseHelper.columnPeriodStart} >= ? AND ${DatabaseHelper.columnPeriodEnd} <= ?',
      whereArgs: [userId, _dateFormat.format(startDate), _dateFormat.format(endDate)],
    );

    // 获取时间范围内的症状记录
    final allSymptoms = _prefsService.getObjectList(SharedPreferencesService.keySymptoms);
    final List<Map<String, dynamic>> symptomMaps = allSymptoms
      .where((symptom) {
        try {
          final symptomDate = _dateFormat.parse(symptom['date']);
          return !symptomDate.isBefore(startDate) && !symptomDate.isAfter(endDate);
        } catch (e) {
          return false;
        }
      })
      .toList();

    // 处理症状数据，统计每个症状的出现次数和严重程度
    final Map<String, Map<String, dynamic>> symptomStats = {};
    for (var map in symptomMaps) {
      final name = map['name'];
      final severity = map['severity'];
      
      if (symptomStats.containsKey(name)) {
        symptomStats[name]!['count'] = (symptomStats[name]!['count'] as int) + 1;
        symptomStats[name]!['totalSeverity'] = (symptomStats[name]!['totalSeverity'] as int) + severity;
      } else {
        symptomStats[name] = {'count': 1, 'totalSeverity': severity};
      }
    }

    // 计算平均周期和经期长度
    final allPeriods = await getUserPeriodsAsObjects(userId);
    final cycleData = calculateAverageCycleData(allPeriods);

    // 转换为Period对象列表
    final periods = List.generate(periodMaps.length, (i) {
      return Period(
        id: periodMaps[i]['id'],
        startDate: _dateFormat.parse(periodMaps[i]['start_date']),
        endDate: _dateFormat.parse(periodMaps[i]['end_date']),
        flowIntensity: periodMaps[i]['flow'],
        note: periodMaps[i]['note'],
        userId: periodMaps[i]['user_id'],
      );
    });

    // 生成报告
    return HealthReport(
      startDate: startDate,
      endDate: endDate,
      periods: periods,
      symptomStats: symptomStats,
      avgCycleLength: cycleData['avgCycleLength']!,
      avgPeriodLength: cycleData['avgPeriodLength']!,
      periodCount: periodMaps.length,
      regularity: calculateCycleRegularity(allPeriods),
    );
  }

  // 计算周期规律性
  double calculateCycleRegularity(List<Period> periods) {
    if (periods.length < 3) return 0.0;

    List<int> cycleLengths = [];
    int count = math.min(periods.length - 1, 6);

    for (int i = 0; i < count; i++) {
      final length = periods[i].startDate.difference(periods[i + 1].startDate).inDays.abs();
      cycleLengths.add(length);
    }

    // 计算标准差
      final avg = cycleLengths.reduce((a, b) => a + b) / cycleLengths.length;
      final variance = cycleLengths.map((length) => math.pow(length - avg, 2)).reduce((a, b) => a + b) / cycleLengths.length;
      final stdDev = math.sqrt(variance);

    // 标准差越小，规律性越高
    // 标准差为0表示完全规律，返回1.0
    // 标准差大于5表示非常不规律，返回0.0
    return math.max(0.0, math.min(1.0, 1.0 - stdDev / 5.0));
  }

  // 获取今天的预测信息
  Future<TodayPrediction> getPredictionForToday() async {
    try {
      // 获取当前用户信息（假设用户ID为1）
      const userId = 1;
      
      // 获取用户的经期记录
      final periods = await getUserPeriodsAsObjects(userId);
      
      // 计算平均周期数据
      final cycleData = calculateAverageCycleData(periods);
      final avgCycleLength = cycleData['avgCycleLength'] ?? 28;
      final avgPeriodLength = cycleData['avgPeriodLength'] ?? 5;
      
      // 获取今天的状态
      final today = DateTime.now();
      final todayStatus = await getDayStatus(userId, today);
      
      // 获取最近的经期记录
      Period? latestPeriod;
      if (periods.isNotEmpty) {
        latestPeriod = periods.first;
      }
      
      // 计算下次经期日期
      DateTime nextPeriodDate;
      if (latestPeriod != null) {
        nextPeriodDate = latestPeriod.startDate.add(Duration(days: avgCycleLength));
        // 如果下次经期日期已经过去，继续计算下一个周期
        while (nextPeriodDate.isBefore(today)) {
          nextPeriodDate = nextPeriodDate.add(Duration(days: avgCycleLength));
        }
      } else {
        nextPeriodDate = today.add(Duration(days: avgCycleLength));
      }
      
      // 计算距离下次经期的天数
      final daysUntilNextPeriod = nextPeriodDate.difference(today).inDays;
      
      // 计算排卵期（通常在下次月经前14天）
      final ovulationDate = nextPeriodDate.subtract(Duration(days: 14));
      final isOvulation = today.isAfter(ovulationDate.subtract(Duration(days: 1))) && 
                          today.isBefore(ovulationDate.add(Duration(days: 1)));
      
      // 计算怀孕几率
      double pregnancyRate;
      if (isOvulation) {
        pregnancyRate = 0.8; // 排卵期怀孕几率最高
      } else if (today.isAfter(ovulationDate.subtract(Duration(days: 2))) && 
                 today.isBefore(ovulationDate.add(Duration(days: 2)))) {
        pregnancyRate = 0.6; // 易孕期
      } else {
        pregnancyRate = 0.1; // 安全期
      }
      
      // 创建周期信息对象
      final cycleInfo = CycleInfo(
        cycleLength: avgCycleLength,
        periodLength: avgPeriodLength,
        nextPeriodDate: nextPeriodDate,
        ovulationDate: ovulationDate,
        pregnancyRate: pregnancyRate * 100,
        daysUntilNextPeriod: daysUntilNextPeriod,
        daysUntilOvulation: ovulationDate.difference(today).inDays,
        healthScore: 85,
        healthStatus: '良好',
        fertilityWindow: isOvulation ? '排卵期' : (pregnancyRate > 0.5 ? '易孕期' : '安全期'),
        recommendations: _getRecommendations(todayStatus, isOvulation),
        predictionConfidence: (calculatePredictionAccuracy(periods.length) * 100).round(),
      );
      
      // 返回今天的预测信息
      return TodayPrediction(
        status: _getStatusText(todayStatus, isOvulation),
        advice: _getAdviceText(todayStatus, isOvulation, daysUntilNextPeriod),
        isPeriod: todayStatus == 'period',
        isOvulation: isOvulation,
        cycleInfo: cycleInfo,
        discharge: _getDischargeInfo(todayStatus, isOvulation),
        symptoms: [], // 可以从症状记录中获取
      );
    } catch (e) {
      debugPrint('获取今天预测信息失败: $e');
      // 返回默认预测信息
      return TodayPrediction(
        status: '正常',
        advice: '保持健康的生活方式',
        isPeriod: false,
        isOvulation: false,
        cycleInfo: CycleInfo(
          cycleLength: 28,
          periodLength: 5,
          nextPeriodDate: DateTime.now().add(Duration(days: 28)),
          ovulationDate: DateTime.now().add(Duration(days: 14)),
          pregnancyRate: 3.2,
          daysUntilNextPeriod: 28,
          daysUntilOvulation: 14,
          healthScore: 85,
          healthStatus: '良好',
          fertilityWindow: '近期',
          recommendations: ['保持健康作息', '注意营养均衡'],
          predictionConfidence: 70,
        ),
        discharge: '正常',
        symptoms: [],
      );
    }
  }
  
  // 获取状态文本
  String _getStatusText(String todayStatus, bool isOvulation) {
    if (todayStatus == 'period') return '经期中';
    if (isOvulation) return '排卵期';
    if (todayStatus == 'predicted_period') return '预测经期';
    return '安全期';
  }
  
  // 获取建议文本
  String _getAdviceText(String todayStatus, bool isOvulation, int daysUntilNextPeriod) {
    if (todayStatus == 'period') return '注意休息，保持温暖';
    if (isOvulation) return '易孕期，注意避孕或备孕';
    if (daysUntilNextPeriod <= 3) return '经期将至，做好准备';
    return '保持良好生活习惯';
  }
  
  // 获取分泌物信息
  String _getDischargeInfo(String todayStatus, bool isOvulation) {
    if (isOvulation) return '透明拉丝状';
    if (todayStatus == 'period') return '经血';
    return '正常';
  }
  
  // 获取建议
  List<String> _getRecommendations(String todayStatus, bool isOvulation) {
    final recommendations = <String>[];
    
    if (todayStatus == 'period') {
      recommendations.add('多喝热水');
      recommendations.add('避免剧烈运动');
    } else if (isOvulation) {
      recommendations.add('注意避孕或备孕');
      recommendations.add('保持心情愉快');
    } else {
      recommendations.add('保持健康作息');
      recommendations.add('注意营养均衡');
    }
    
    return recommendations;
  }

  // 获取周期信息
  Future<CycleInfo> getCycleInfo() async {
    // 这里需要实现获取当前周期信息的逻辑
    // 暂时返回一个默认的CycleInfo对象
    return CycleInfo(
      cycleLength: 28,
      periodLength: 5,
      nextPeriodDate: DateTime.now().add(Duration(days: 28)),
      ovulationDate: DateTime.now().add(Duration(days: 14)),
      pregnancyRate: 0.3,
      daysUntilNextPeriod: 28,
      daysUntilOvulation: 14,
      healthScore: 85,
      healthStatus: '良好',
      fertilityWindow: '近期',
      recommendations: ['保持健康作息', '注意营养均衡'],
      predictionConfidence: 70
    );
  }

  // 获取最近的周期记录
  Future<List<Period>> getRecentCycles() async {
    // 这里需要实现获取最近周期记录的逻辑
    // 暂时返回空列表
    return [];
  }

  // 获取某天的状态（经期、排卵期、安全期）
  Future<String> getDayStatus(int userId, DateTime date) async {
    // 检查是否在实际记录的经期内
    final allPeriods = _prefsService.getObjectList(SharedPreferencesService.keyPeriods);
    final bool isInPeriod = allPeriods.any((period) {
      if (period['user_id'] != userId) return false;
      
      try {
        final startDate = _dateFormat.parse(period['start_date']);
        final endDate = _dateFormat.parse(period['end_date']);
        return !date.isBefore(startDate) && !date.isAfter(endDate);
      } catch (e) {
        return false;
      }
    });

    if (isInPeriod) {
      return 'period';
    }

    // 预测未来状态
    final nextThreeMonths = date.add(Duration(days: 90));
    final monthDiff = (nextThreeMonths.year - date.year) * 12 + (nextThreeMonths.month - date.month);
    
    // 获取预测数据
    final periodPredictions = await predictNextPeriods(userId, monthDiff + 1);
    final ovulationPredictions = await predictOvulationPeriod(userId, monthDiff + 1);

    // 检查是否在预测的经期内
    for (var prediction in periodPredictions) {
      if (date.isAfter(prediction.startDate.subtract(Duration(days: 1))) && 
          date.isBefore(prediction.endDate.add(Duration(days: 1)))) {
        return 'predicted_period';
      }
    }

    // 检查是否在预测的排卵期内
    for (var prediction in ovulationPredictions) {
      if (date.isAfter(prediction.startDate.subtract(Duration(days: 1))) && 
          date.isBefore(prediction.endDate.add(Duration(days: 1)))) {
        return 'ovulation';
      }
    }

    // 默认为安全期
    return 'safe';
  }
  
  // 检查今天是否是经期
  Future<bool> isPeriodActiveToday(int userId) async {
    try {
      final today = DateTime.now();
      final allPeriods = _prefsService.getObjectList(SharedPreferencesService.keyPeriods);
      
      for (var period in allPeriods) {
        if (period['user_id'] == userId) {
          final startDate = _dateFormat.parse(period['start_date']);
          final endDate = _dateFormat.parse(period['end_date']);
          
          // 检查今天是否在这个经期范围内
          if (!today.isBefore(startDate) && !today.isAfter(endDate)) {
            return true;
          }
        }
      }
      
      return false;
    } catch (e) {
      debugPrint('检查今天是否是经期失败: $e');
      return false;
    }
  }

  // 获取指定月份的数据
  Future<List<PeriodModel>> getMonthData(int year, int month) async {
    final firstDay = DateTime(year, month, 1);
    final lastDay = DateTime(year, month + 1, 0);
    
    final allPeriods = _prefsService.getObjectList(SharedPreferencesService.keyPeriods);
     final List<Map<String, dynamic>> periodMaps = allPeriods
       .where((period) {
         final startDate = _dateFormat.parse(period['start_date']);
         return startDate.isAfter(firstDay.subtract(Duration(days: 1))) && 
                startDate.isBefore(lastDay.add(Duration(days: 1)));
       })
       .toList();

    final List<PeriodModel> result = [];
    final now = DateTime.now();
    
    // 转换数据库记录为PeriodModel
    for (var map in periodMaps) {
      final startDate = _dateFormat.parse(map['start_date']);
      final endDate = _dateFormat.parse(map['end_date']);
      
      // 为经期内的每一天创建一个PeriodModel
      for (var day = startDate; !day.isAfter(endDate); day = day.add(Duration(days: 1))) {
        result.add(PeriodModel(
          id: map['id'],
          date: day,
          isPeriod: true,
          isOvulation: false,
          isToday: day.year == now.year && day.month == now.month && day.day == now.day,
          isPredictedPeriod: false,
          isPossiblePeriod: false,
          notes: map['note'],
          flowLevel: (map['flow'] as int?)?.toDouble(),
        ));
      }
    }
    
    return result;
  }
}

// 健康报告类
class HealthReport {
  final DateTime startDate;
  final DateTime endDate;
  final List<Period> periods;
  final Map<String, Map<String, dynamic>> symptomStats;
  final int avgCycleLength;
  final int avgPeriodLength;
  final int periodCount;
  final double regularity;

  HealthReport({
    required this.startDate,
    required this.endDate,
    required this.periods,
    required this.symptomStats,
    required this.avgCycleLength,
    required this.avgPeriodLength,
    required this.periodCount,
    required this.regularity,
  });

  // 获取规律性评级
  String getRegularityRating() {
    if (regularity >= 0.8) return '非常规律';
    if (regularity >= 0.6) return '比较规律';
    if (regularity >= 0.4) return '一般';
    if (regularity >= 0.2) return '不太规律';
    return '很不规律';
  }

  // 获取最常见的症状
  List<MapEntry<String, Map<String, dynamic>>> getMostCommonSymptoms() {
    final entries = symptomStats.entries.toList();
    entries.sort((a, b) => b.value['count'].compareTo(a.value['count']));
    return entries.take(3).toList();
  }
}

// 周期预测类
class PeriodPrediction {
  final DateTime startDate;
  final DateTime endDate;
  final double accuracy;
  final String type; // 'period', 'ovulation', 'safe'

  PeriodPrediction({
    required this.startDate,
    required this.endDate,
    required this.accuracy,
    required this.type,
  });
}